package com.settlement.system.controller;

import com.settlement.system.common.enums.ReturnStatusEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.common.annotation.LoggerProfile;
import com.settlement.system.model.entity.common.TblRrChannel;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.service.IBaseService;
import com.settlement.system.service.ITblRrChannelService;
import com.settlement.system.common.util.common.FasUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.fastjson2.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 渠道 前端控制器
 * @author xiaochuan
 * @since 2021-12-01
 */

@Api(tags = "渠道",description = "渠道")
@RestController
@Slf4j
@RequestMapping("/rr/channel")
public class TblRrChannelController extends ExcelController<TblRrChannel> {

    @Resource
    private ITblRrChannelService tblRrChannelService;

    @Override
    public IBaseService init() {
        return tblRrChannelService;
    }


    @Override
    public Class<?> getModelClass() {
        return TblRrChannel.class;
    }

    @Override
    protected void setParamsModel(Map<String, Object> model) {
        FasUtil.formatInQueryCondition(model, "channelNo");
        super.setParamsModel(model);
    }

    @Override
    public String verifyImportObject(TblRrChannel tblRrChannel, AnalysisContext analysisContext) {
        String message = super.verifyImportObject(tblRrChannel,analysisContext);
        if(StringUtils.isNotEmpty(message)){
            return message;
        }
        try {
            List<TblRrChannel> tblRrVoucherTypes = tblRrChannelService.selectByParams(tblRrChannel);
            if(!CollectionUtils.isEmpty(tblRrVoucherTypes)){
                return "渠道或渠道编码已存在";
            }
        } catch (ServiceException e) {
            e.printStackTrace();
            return "校验时查询出错";
        }

        return null;
    }

    @Override
    protected void saveData(List<TblRrChannel> datas) throws ServiceException {

        List<String> list = new ArrayList<>();
        for(TblRrChannel data : datas){
            String toString = data.toString();
            if(list.contains(toString)){
                throw new ServiceException("有两行数据重复");
            }else{
                list.add(toString);
            }
        }

        /*list = new ArrayList<>();
        for(TblRrChannel data : datas){
            String sort = data.getSort();
            if(list.contains(sort)){
                throw new ServiceException("有两行排序重复");
            }else{
                list.add(sort);
            }
        }*/

        super.saveData(datas);
    }

    @Override
    protected ObjectDataResponse insert(@RequestBody TblRrChannel model, HttpServletRequest request) throws ServiceException {
        try{
            String message = super.verifyImportObject(model,null);
            if(StringUtils.isNotEmpty(message)){
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), message);
            }

            List<TblRrChannel> tblRrVoucherTypes = tblRrChannelService.selectByParams(model);
            if(!CollectionUtils.isEmpty(tblRrVoucherTypes)){
                //return new ObjectDataResponse(500, "新增失败，请联系管理员！");
                log.info("渠道或渠道编码已存在", JSON.toJSONString(model));
                return new ObjectDataResponse(ReturnStatusEnum.DUPLICATE_DATA.getValue(), "渠道或编码已存在");
                //return "渠道或编码已存在";
            }
        }catch (Exception ex){
            log.info("校验时查询出错",ex);
            return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), "校验时查询出错");
        }
        return super.insert(model, request);
    }

    @ApiOperation(value = "check")
    @LoggerProfile(methodNote="check")
    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public ObjectDataResponse check(@RequestBody TblRrChannel model) {
        try {
            String message = verifyImportObject(model,null);
            if(StringUtils.isNotEmpty(message)){
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), message);
            }
        } catch (Exception ex) {
            log.error("check error", ex);
            return new ObjectDataResponse(500, "服务器异常");
        }
        return new ObjectDataResponse(200, "success");
    }

    @Override
    protected ObjectDataResponse batchDelete(@RequestBody List<TblRrChannel> deleteList, HttpServletRequest request) throws ServiceException {
        try{
            String message = checkDeleteList(deleteList);
            if (StringUtils.isNotEmpty(message)) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), message);
            }
        } catch (Exception ex) {
            log.info("更新数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL);
        }
        return super.batchDelete(deleteList, request);
    }

    String checkDeleteList(List<TblRrChannel> deleteList) throws ServiceException {
        String [] usedMenus = new String[]{"RR-记账项目","RR-账号设置","RR-店铺配置"};
        String usedMenu = null;
        TblRrChannel usedChannel = null;
        String tip = "渠道编码或渠道名称在 菜单 已使用";
        Map<String,Object> map = new HashMap();
        for(TblRrChannel channel : deleteList){
            map = new HashMap<>();
            map.put("id",channel.getId());

            List<TblRrChannel> objects = tblRrChannelService.selectByParam(map);
            if(!objects.isEmpty()){
                channel = objects.get(0);
            }else{
                log.info("数据id"+channel.getId()+"已被删除");
                continue;
            }
            Integer integer = tblRrChannelService.selectUsedCount(channel);
            if(integer>=4){
                usedMenu = usedMenus[0];
            }else if(integer >=2){
                usedMenu = usedMenus[1];
            }else if(integer >=1){
                usedMenu = usedMenus[2];
            }
            if(integer>0){
                usedChannel = channel;
                break;
            }
        }
        if(usedMenu!=null){
            tip = tip.replace("渠道编码","渠道编码"+usedChannel.getChannelNo())
                    .replace("渠道名称","渠道名称"+usedChannel.getChannelName())
                    .replace("菜单",usedMenu);
            return tip;
        }
        return null;
    }


}

